<template>
    <div class="app-container" v-if="canList">
        <!--        <div class="filter-container">-->
        <!--            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"-->
        <!--                      placeholder="上级"-->
        <!--                      v-model="listQuery['parent.name']">-->
        <!--            </el-input>-->
        <!--            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"-->
        <!--                      placeholder="名称"-->
        <!--                      v-model="listQuery['menu.name']">-->
        <!--            </el-input>-->
        <!--            &lt;!&ndash;      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"&ndash;&gt;-->
        <!--            &lt;!&ndash;                placeholder="URL"&ndash;&gt;-->
        <!--            &lt;!&ndash;                v-model="listQuery.url">&ndash;&gt;-->
        <!--            &lt;!&ndash;      </el-input>&ndash;&gt;-->
        <!--            &lt;!&ndash;      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"&ndash;&gt;-->
        <!--            &lt;!&ndash;                placeholder="授权"&ndash;&gt;-->
        <!--            &lt;!&ndash;                v-model="listQuery.perms">&ndash;&gt;-->
        <!--            &lt;!&ndash;      </el-input>&ndash;&gt;-->
        <!--            <el-select @change='handleFilter' clearable class="filter-item" style="width: 130px"-->
        <!--                       v-model="listQuery['menu.type']"-->
        <!--                       placeholder="类型">-->
        <!--                <el-option v-for="(item,index) in  typeOptions" :key="item" :label="item" :value="index">-->
        <!--                </el-option>-->
        <!--            </el-select>-->
        <!--            <el-select @change='handleFilter' clearable class="filter-item" style="width: 130px"-->
        <!--                       v-model="listQuery['menu.status']"-->
        <!--                       placeholder="启用">-->
        <!--                <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">-->
        <!--                </el-option>-->
        <!--            </el-select>-->

        <!--            <el-button style="margin-left: 10px;" class="filter-item" type="primary" v-waves icon="el-icon-search"-->
        <!--                       @click="handleFilter">查找-->
        <!--            </el-button>-->
        <!--&lt;!&ndash;            <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"&ndash;&gt;-->
        <!--&lt;!&ndash;                       v-if="canSave" icon="el-icon-edit">添加&ndash;&gt;-->
        <!--&lt;!&ndash;            </el-button>&ndash;&gt;-->
        <!--&lt;!&ndash;            <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"&ndash;&gt;-->
        <!--&lt;!&ndash;                       @click="handleDownload">导出&ndash;&gt;-->
        <!--&lt;!&ndash;            </el-button>&ndash;&gt;-->
        <!--        </div>-->

        <el-table row-key="menuId" :tree-props="{children: 'list'}" :key='tableKey' :data="list" v-loading="listLoading"
                  border fit highlight-current-row
                  style="width: 100%;">


            <el-table-column align="center" label="序号">
                <template slot-scope="scope">
                    <span>{{scope.row.menuId}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="上级">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.parent==null?'无':scope.row.parent.name}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" label="名称">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="URL">
                <template slot-scope="scope">
                    <span>{{scope.row.url}}</span>
                </template>
            </el-table-column>
            <!--      <el-table-column align="center" label="授权">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{scope.row.menu.perms}}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <!--      <el-table-column align="center" label="图标">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{scope.row.menu.icon}}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <el-table-column align="center" label="排序">
                <template slot-scope="scope">
                    <span>{{scope.row.orderNum}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="类型">
                <template slot-scope="scope">
                    <span>
                        <el-tag :type="tagTypes[scope.row.type]"> {{typeOptions[scope.row.type]}}</el-tag>

                    </span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="启用">
                <template slot-scope="scope">

                    <el-tag :type="tagTypes[scope.row.status]"> {{statusOptions[scope.row.status]}}</el-tag>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope.row)">编辑
                    </el-button>
                    <!--                    <el-button v-if="canSave" size="mini" type="danger"-->
                    <!--                               @click="handleDelete(scope.row.menu)">删除-->
                    <!--                    </el-button>-->
                </template>
            </el-table-column>

        </el-table>

        <!--        <div class="pagination-container">-->
        <!--            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"-->
        <!--                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"-->
        <!--                           layout="total, sizes, prev, pager, next, jumper" :total="total">-->
        <!--            </el-pagination>-->
        <!--        </div>-->

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"
                     style='width: 450px; margin-left:50px;'>
                <el-form-item label="上级" prop="parentId">
                    <el-input placeHolder="父菜单ID，一级菜单为0" v-model="temp.parentId"></el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="temp.name"></el-input>
                </el-form-item>
                <el-form-item label="URL" prop="url">
                    <el-input v-model="temp.url"></el-input>
                </el-form-item>
                <el-form-item label="授权" prop="perms">
                    <el-input placeHolder="授权(多个用逗号分隔，如：user:list,user:create)" v-model="temp.perms"></el-input>
                </el-form-item>
                <el-form-item label="图标" prop="icon">
                    <el-input v-model="temp.icon"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <el-input v-model="temp.orderNum"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="status">
                    <el-select class="filter-item" v-model="temp.type" placeholder="类型">
                        <el-option v-for="(item,index) in  typeOptions" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="启用" prop="status">
                    <el-select class="filter-item" v-model="temp.status" placeholder="启用">
                        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
                <el-button v-else type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        padding-bottom: 20px;
    }
</style>

<script>
    import {list, save, update, remove, getPerms} from '@/api/sys_menu'
    import waves from '@/directive/waves' // 水波纹指令


    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                tableKey: 0,
                list: [],
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 20
                },
                typeOptions: ["目录", "菜单", "按钮"],
                tagTypes: ['info', '', 'warning'],
                statusOptions: ["启用", "关闭"],
                temp:
                    {
                        menuId: null,
                        parentId: null,
                        name: null,
                        url: null,
                        perms: null,
                        type: null,
                        icon: null,
                        orderNum: null,
                        status: null
                    }
                ,
                dialogFormVisible: false,
                dialogStatus:
                    '',
                textMap:
                    {
                        update: '修改',
                        create:
                            '新增'
                    }
                ,
                rules:
                    {
                        parentId: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        name: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        url: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        perms: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        type: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'blur'
                            }
                        ]
                        ,
                        icon: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        orderNum: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        status: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'blur'
                            }
                        ]
                    }
                ,
                downloadLoading: false,
                qData:
                    {
                        token: '',
                        key:
                            ''
                    }
            }
        },
        created() {
            this.getList()
        },
        computed: {
            ...mapGetters([
                'perms'
            ]),
            canSave() {
                return hasAuth(this.perms, 'sys:menu:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'sys:menu:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'sys:menu:update')
            },
            canList() {
                return hasAuth(this.perms, 'sys:menu:list')
            }
        },
        methods: {
            getList() {
                this.listLoading = true
                // list(this.listQuery)
                // list(this.listQuery).then(response => {
                getPerms().then(response => {
                    this.list = response.data
                    console.log(this.list)
                    // this.total = response.data.total
                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片

            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
            },
            resetTemp(row) {

                this.temp = {}
                if (row) {
                    this.temp = Object.assign({}, row) // copy obj
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(row) {
                this.beforeFormShow(row)
                this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                const ids = [this.temp.menuId]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    for (const v of this.list
                        ) {
                        if (v.menuId === this.temp.menuId) {
                            const index = this.list.indexOf(v)
                            this.list.splice(index, 1)
                            break
                        }
                    }
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(row) {
                this.beforeFormShow(row)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            //移除无用
                            delete this.temp.checked
                            delete this.temp.list
                            update(this.temp).then(() => {
                                //重新获取数据
                                this.getList()
                                // for (const v of this.list
                                //     ) {
                                //     if (v.menuId === this.temp.menuId) {
                                //         const index = this.list.indexOf(v)
                                //         this.list.splice(index, 1, this.temp)
                                //         break
                                //     }
                                // }
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                this.dialogFormVisible = false
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = [
                        '序号'
                        ,
                        '父菜单ID，一级菜单为0'
                        ,
                        '菜单名称'
                        ,
                        '菜单URL'
                        ,
                        '授权(多个用逗号分隔，如：user:list,user:create)'
                        ,
                        '菜单图标'
                        ,
                        '排序'
                        ,
                        '类型'
                        ,
                        '启用'
                    ]
                    const filterVal = ['id'
                        , 'parentId'
                        , 'name'
                        , 'url'
                        , 'perms'
                        , 'icon'
                        , 'orderNum'
                        ,
                        'type'
                        ,
                        'status'
                    ]
                    const data = this.formatJson(filterVal, this.list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                        return v[j]
                    }
                ))
            },
        }
    }
</script>
